﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.IO;
using Microsoft.Win32;

namespace iSmartCreatorApp
{
    /// <summary>
    /// Interaction logic for NewDocument.xaml
    /// </summary>
    public partial class NewDocument : Window
    {
        public static string pageTitle; //Page title
        public static string pageBody; //Page body
        public static string pageDTD; //Page DTD
        public static string pageHtmlType; //Page html type

        //Constructor on load form NewDocument
        public NewDocument()
        {
            InitializeComponent();
            RadioBtnNewFile1.IsChecked = true;
            ChckBxNewFile2.IsChecked = true;
            TxtBxFileName.Focus();
        }

        //Button "Cancel"
        private void BtnNewFileCancel_Click(object sender, RoutedEventArgs e)
        {
            this.Close();
        }

        //RadioButton "A blank template" on Click
        private void RadioBtnNewFile2_Click(object sender, RoutedEventArgs e)
        {
            ChckBxNewFile1.IsEnabled = false;
            ChckBxNewFile2.IsEnabled = false;
        }

        //RadioButton "A blank Document" on Click
        private void RadioBtnNewFile1_Click(object sender, RoutedEventArgs e)
        {
            ChckBxNewFile1.IsEnabled = true;
            ChckBxNewFile2.IsEnabled = true;
        }

        //Creating file
        public void CreateNewFile(Paragraph p, FlowDocument f, MainWindow m)
        {
            string[] fileStr = File.ReadAllLines("template.html");
            var enumerator = MainWindow.dictionary.GetEnumerator();
            string currentKey;
            string currentVal;


            while (enumerator.MoveNext())
            {
                currentKey = enumerator.Current.Key;
                currentVal = enumerator.Current.Value;

                for (int i = 0; i < fileStr.Length; i++)
                {
                    if (fileStr[i].Contains(currentKey))
                    {
                        fileStr[i] = fileStr[i].Replace(currentKey, currentVal);
                    }
                }
            }

            foreach (var i in fileStr)
            {
                p.Inlines.Add(i + "\n");
            }

            f.Blocks.Add(p);
            m.TabControlMain.Visibility = Visibility.Visible;

            #region CreatingDocumentOnTabControl

            TabItem item = new TabItem {Header = MainWindow.fileName};

            bool b;
            foreach (TabItem i in m.TabControlMain.Items)
            {
                b = i.Header.Equals(item.Header);
                if (b)
                {
                    MessageBox.Show("You already have file with this name!", "iSmart Creator", MessageBoxButton.OK);
                    return;
                }
            }

            TabControl control = new TabControl {TabStripPlacement = Dock.Bottom};
            TabItem editor = new TabItem {Header = "editor"};
            TabItem sourceCode = new TabItem {Header = "source code"};
            TabItem preview = new TabItem {Header = "preview"};

            MainWindow.currentRTBHtml = new RichTextBox
            {
                IsReadOnly = true,
                VerticalScrollBarVisibility = ScrollBarVisibility.Auto,
                HorizontalScrollBarVisibility = ScrollBarVisibility.Auto
            };
            MainWindow.currentRTBUser = new RichTextBox
            {
                VerticalScrollBarVisibility = ScrollBarVisibility.Auto,
                HorizontalScrollBarVisibility = ScrollBarVisibility.Auto
            };
            MainWindow.currentWebBrowser = new WebBrowser();
            editor.Content = MainWindow.currentRTBUser;
            sourceCode.Content = MainWindow.currentRTBHtml;
            preview.Content = MainWindow.currentWebBrowser;

            MainWindow.currentRTBHtml.Document = f;

            control.Items.Add(editor);
            control.Items.Add(sourceCode);
            control.Items.Add(preview);

            item.Content = control;
            item.IsSelected = true;
            m.TabControlMain.Items.Add(item);
            #endregion

            TreeViewItem element = new TreeViewItem {Header = MainWindow.fileName};
            DirectoryNameWindow.MainTreeViewItem.Items.Add(element);
            DirectoryNameWindow.MainTreeViewItem.IsExpanded = true;

            m.MenuItemSave.IsEnabled = true;
            m.MenuItemSaveAs.IsEnabled = true;
            m.BtnSave.IsEnabled = true;
            m.MenuItemChangeTitle.IsEnabled = true;
            m.BtnLink.IsEnabled = true;
            m.BtnImage.IsEnabled = true;
            m.BtnTable.IsEnabled = true;

            FileStream stream = new FileStream(MainWindow.projectFileDirectory + "\\" + MainWindow.fileName,
                                               FileMode.Create);
            using (stream)
            {
                string str = new TextRange(MainWindow.currentRTBHtml.Document.ContentStart, MainWindow.currentRTBHtml.Document.ContentEnd).Text;

                StreamWriter writer = new StreamWriter(stream);

                using (writer)
                {
                    writer.Write(str);
                }
            }
            this.Close();
        }

        //Button "Create" on Click
        private void BtnNewFileCreate_Click(object sender, RoutedEventArgs e)
        {
            if (TxtBxFileName.Text == "")
            {
                MessageBox.Show("Input file name!", "Error", MessageBoxButton.OK, MessageBoxImage.Error);
            }

            else
            {
                MainWindow.fileName = TxtBxFileName.Text + ".html";
                pageTitle = TxtBxTitle.Text;

                MainWindow.dictionary["$title"] = pageTitle;

                var mainWindow = Owner as MainWindow; //Making reference to MainForm as owner
                var paragraph = new Paragraph();
                var flow = new FlowDocument();

                if (mainWindow != null)
                {
                    //Checking if RadioButton "A blank template" is checked
                    if (RadioBtnNewFile2.IsChecked == true)
                    {
                        pageDTD =
                            "!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\" \"http://www.w3.org/TR/html4/loose.dtd\"";
                        pageHtmlType = " template=\"true\"";

                        MainWindow.dictionary["$DTD"] = pageDTD;
                        MainWindow.dictionary["$html"] = pageHtmlType;

                        CreateNewFile(paragraph, flow, mainWindow);
                    }

                        //Checking if RadioButton "A blank Document" is checked
                    else if (RadioBtnNewFile1.IsChecked == true && ChckBxNewFile1.IsChecked == false &&
                             ChckBxNewFile2.IsChecked == false)
                    {
                        pageDTD =
                            "!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\" \"http://www.w3.org/TR/html4/loose.dtd\"";
                        pageHtmlType = "";

                        MainWindow.dictionary["$DTD"] = pageDTD;
                        MainWindow.dictionary["$html"] = pageHtmlType;

                        CreateNewFile(paragraph, flow, mainWindow);
                    }

                        //Checking if RadioButton "A blank Document", CheckBox "Strict DTD" are checked
                    else if (RadioBtnNewFile1.IsChecked == true && ChckBxNewFile2.IsChecked == true &&
                             ChckBxNewFile1.IsChecked == false)
                    {
                        pageDTD =
                            "!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.01//EN\" \"http://www.w3.org/TR/html4/strict.dtd\"";
                        pageHtmlType = "";

                        MainWindow.dictionary["$DTD"] = pageDTD;
                        MainWindow.dictionary["$html"] = pageHtmlType;

                        CreateNewFile(paragraph, flow, mainWindow);
                    }

                        //Checking if RadioButton "A blank Document", CheckBox "Create XHTML Document" are checked
                    else if (RadioBtnNewFile1.IsChecked == true && ChckBxNewFile1.IsChecked == true &&
                             ChckBxNewFile2.IsChecked == false)
                    {
                        pageDTD =
                            "!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\"";
                        pageHtmlType = " xmlns=\"http://www.w3.org/1999/xhtml\"";

                        MainWindow.dictionary["$DTD"] = pageDTD;
                        MainWindow.dictionary["$html"] = pageHtmlType;

                        CreateNewFile(paragraph, flow, mainWindow);
                    }

                        //Checking if RadioButton "A blank Document" and all CheckBoxes are checked
                    else if (RadioBtnNewFile1.IsChecked == true && ChckBxNewFile1.IsChecked == true &&
                             ChckBxNewFile2.IsChecked == true)
                    {
                        pageDTD =
                            "!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\"";
                        pageHtmlType = " xmlns=\"http://www.w3.org/1999/xhtml\"";

                        MainWindow.dictionary["$DTD"] = pageDTD;
                        MainWindow.dictionary["$html"] = pageHtmlType;

                        CreateNewFile(paragraph, flow, mainWindow);
                    }
                }
            }
        }
    }
}